/*
 * 补发单新建
 * */
var skuId = "";

$(document).ready(function() {
    skuId = extractSkuId();
    updateCost(skuId);
	$("#newForm").validate({
        debug:true,
        errorPlacement: function(error, element)
        {
            error.insertAfter(element);
        }
    });
	
	$("#curtCost", $("#newForm")).inputmask("9{1,8}[.99]", {
        greedy: false,
        placeholder: ''
    });
});

//设置输入框和下拉框不可用的title属性
function setInputSelectTitle(){
		var length = $("input").length;
		for(var i=0;i<length;i++){
			if($("input")[i].disabled || $("input")[i].readOnly){
				$("input")[i].title = $("input")[i].value;
			}
		}
		var sLength = $("select").length;
		for(var i=0;i<sLength;i++){
			if($("select")[i].disabled){
				var childLength = $("select")[i].children.length;
				for(var j=0;j<childLength;j++){
					if($("select")[i].children[j].value == $("select")[i].value){
						$("select")[i].title = $("select")[i].children[j].text;
						break;
					}
				}
				
			}
		}
}

/*
 * 修改情况下回显接口
 */
function updateCost(skuId){
	$.ajax({
	    type : "GET",
	    url : "/goodsCost/getGoodsCost.action",
	    data : {
		    "skuId" : skuId
	    },
	    contentType : "application/json;charset=utf-8",
	    dataType : "json",
	    async : true,// 同步
	    success : function(data) {
		    if (data.result == "success") {
			    $("#goodsCode").val(data.data.goodsCode);
			    $("#goodsName").val(data.data.goodsName);
			    $("#skuCode").val(data.data.skuCode);
			    $("#skuName").val(data.data.skuName);			    
			    var costPrice = parseFloat(data.data.costPrice).toFixed(2);
			    $("#origCost").val(costPrice);
			    $("#curtCost").val(costPrice);
			    $("#remark").val("");
		    	setInputSelectTitle();
		    } else {
			    window.top.window.showModalAlert(data.msg);
		    }
	    },
	    error : function(XMLHttpRequest, textStatus) {
		    if (XMLHttpRequest.status == 500) {
			    var result = eval("(" + XMLHttpRequest.responseText + ")");
			    alert(result.errorObject.errorText);
		    }
	    }
	});
}

/*function inputRestriction(obj){
	obj.value = obj.value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
	obj.value = obj.value.replace(/^\./g,""); //验证第一个字符是数字
	obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个, 清除多余的
	obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
	obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数
	}*/


function saveCostChange(context) {

	if(!$("#newForm").valid()) {
        return;
    }	
	var goodsCostVO = {
	    "skuId" : skuId,	    
	    "goodsCode" : $("#goodsCode").val(),
	    "goodsName" : $("#goodsName").val(),
	    "skuCode" : $("#skuCode").val(),
	    "skuName" : $("#skuName").val(),
	    "costPrice" : $("#curtCost").val(),
	    "origCost" : $("#origCost").val(),
	    "curtCost" : $("#curtCost").val(),
	    "remark" : $("#remark").val()
	};
	// console.log(goodsCostVO);
	
	var origCost = parseFloat($("#origCost").val());
	var curtCost = parseFloat($("#curtCost").val());

    if(origCost == 0){
        window.top.window.showModalConfirms("是否确认要变更该成本？", function (){
            changeCost(goodsCostVO);
        });
    } else {
        if (origCost != 0) {
            var increase = Math.abs(curtCost - origCost) / origCost;
        }
        if (curtCost != 0 && increase >= 0.1) {
            window.top.window.showModalConfirms("成本变更前后的上涨或下降幅度达到或超过了10%，是否确认变更？", function () {
                changeCost(goodsCostVO);
            });
        }else if (curtCost == 0) {
            window.top.window.showModalConfirms("变更后成本归零，是否确认要变更该成本？", function () {
                changeCost(goodsCostVO);
            });
        } else {
            window.top.window.showModalConfirms("是否确认要变更该成本？", function () {
                changeCost(goodsCostVO);
            });
        }
    }
	
}

/*
 * 成本变更接口请求
 */
function changeCost(goodsCostVO) {
    var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type : "POST",
        url : "/goodsCost/updateGoodsCost.action",
        data : JSON.stringify(goodsCostVO),
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
//        async : true,// 同步
        success : function(data) {
        	loading.remove();
            if (data.result == "success") {
                window.top.window.showScoMessage("ok", data.data);
                if ($('#btnRefresh', window.top.window.getCurrentIframe().contentWindow.document).length > 0) {
                    $('#btnRefresh', window.top.window.getCurrentIframe().contentWindow.document).click()
                }
                $('#changeCostWindow', window.top.document).find("#btnGoodsCostClose").click();
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}


// 从url中解析按钮名称
// skuId
function extractSkuId() {
	return extractParam("skuId");
};
// ===========公共方法==========

// 获取页面参数
function GetArgsFromHref(sHref, sArgName) {
	var args = sHref.split("?");
	var retval = "";

	if (args[0] == sHref) /* 参数为空 */
	{
		return retval; /* 无需做任何处理 */
	}
	var str = args[1];
	args = str.split("&");
	for (var i = 0; i < args.length; i++) {
		str = args[i];
		var arg = str.split("=");
		if (arg.length <= 1)
			continue;
		if (arg[0] == sArgName)
			retval = arg[1];
	}
	return retval;
}

function extractParam(paramName) {
	var returnString = "";
	var str = window.location.search;
	if (!!str) {
		returnString = GetArgsFromHref(str, paramName);
	}
	return returnString;
}
